package zl.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Receive {

	public static void main(String[] args) throws Exception {
		final DatagramSocket receive = new DatagramSocket(8001);
		receive.connect(InetAddress.getLocalHost(), 8000);
		new Thread(new Runnable() {
			public void run() {
				while (true) {
					DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
					try {
						receive.receive(dp);
					} catch (IOException e) {
						e.printStackTrace();
					}
					System.out.println("收到的"+receive.getInetAddress()+"："+receive.getPort()+"的信息："+new String(dp.getData(),0,dp.getLength()));
				}
			}
		}).start();
		new Thread(new Runnable() {
			public void run() {
				while (true) {
					Scanner in = new Scanner(System.in);
					String str = in.next();
					byte[] strs = str.getBytes();
					DatagramPacket dp = new DatagramPacket(strs, strs.length);
					try {
						receive.send(dp);
					} catch (IOException e) {
						e.printStackTrace();
					}
					if("bye".equalsIgnoreCase(str))
						System.exit(1);
				}
			}
		}).start();
	}
}
